/**
 * 流程图只读模式
 */
import {getQuery} from "../../../framework/common/utils"
 import "./../approveStepReadonly.css"
 import Operations from "../Operations";//只读模式右上角3个按钮
 import React, { useEffect, useRef, useState } from "react";
 import clsx from "clsx";
 import { Tooltip , Input, Radio, Space, Checkbox, Spin, Skeleton } from "antd";
 import { getApproveBtnName, renderName } from "../stepUtility";
 
 //编辑模式的依赖项
 import { NegotiateLogWrap } from "../components/NegotiateLogWrap";
 import "./index.css"
import { useSubscribe } from "../../../framework/common/eventBus";
import { useUpdate } from "ahooks";

 /**
  * 步骤信息
  * step:{
  *  needChoose: 0 //值为1时，存在不确定的审批人选择。但是以前的工作流里面是0为存在不确定的审批人，当后续步骤node有多个节点，NodeConfirm为0的时候，说明该步骤责任人不明确
  *  nodes:[] //该步骤的审批人信息
  *  stepAttrs:{
  *      handle_mode: 'Serial' //Serial串行 Parallel并行
  *      multi_type：'Multi' // Single单人步骤 Multi多人步骤
  *      archived_mode: 'Auto', // 归档方式：Auditor-处理人归档，Auto-系统自动归档 
  *      adjust_auditor: false, // 允许调整责任人 true是 | false否
  *      enable_sign: true, // 开启签章，true开启 | false没开启
  *      no_auditor_rules: ["SkipStep"] //一个数组，如果包含了SkipStep，表示无责任人自动跳过
  *      adjust_auditor: true, // 是否可调整责任方 true可 | false不可
  *      adjust_multi_auditor: true, //调整责任人是否可选择多人 true | false
  *  }
  * }
  */
 
 /**
  * props {}
  * tplData
  * params
  * urlPrefix
  * model edit编辑 readonly只读
  * actual_steps 实际的步骤路径，不包含branch确认步骤，返回给后端
  * approveSteps 步骤信息，包含branch确认步骤，展示在界面
  * setLoading 触发父组件loading，用于给确定按钮加loading状态
  * validateResult 首次加载步骤时的错误信息
  * setActual_steps 父组件更新actual_steps步骤信息的状态方法
  * setAllSteps 父组件更新approveSteps步骤信息的状态方法
  * showValidate 显示步骤校验错误信息
  */
export default function (props) {
    
    //组件依赖数据
    let tplData= props.tplData || {};
    let params = props.params || {};
    const updater = useUpdate();
    useSubscribe("updateApproveStepPrint.update", ()=>{
        updater();
    });
    
    let data = __getStepsDate({
        tplData: tplData
    });//审批流程步骤信息

    if(tplData.hideInfo && tplData.hideInfo.show_audit_records === false){
        return null;
    }
            
    return <div className="approveOpinionWrap">
        <div className="partTitle font-bold pt-3">审批记录</div>
        <div className="group-content mt-10px pb-3">
            <table className="table table-approveOpinion w-full table-fixed break-all" width="100%">
                <colgroup>
                    <col width="35" />
                    <col width="16%"/>
                    <col width="15%"/>
                    <col/>
                    <col width="120"/>
                </colgroup>
                <thead>    
                    <tr>
                        <th className="font-bold text-center">序号</th>
                        <th className="font-bold">审批步骤</th>
                        <th className="font-bold">审批人员</th>
                        <th className="font-bold" >审批意见</th>
                        <th className="font-bold">审批时间</th>
                    </tr>
                </thead>
                <tbody>
                {
                    data.map(function(item, no){
                        return item.nodes.map(function(node, index){
                            return <React.Fragment key={index}>
                                <tr>
                                    {
                                        index == 0
                                        && <>
                                            <td des="序号" className="py-2px text-center" valign="top" rowSpan={item.nodeLength}>{no + 1}</td>
                                            <td des="审批步骤" className="px-5px py-2px" valign="top" rowSpan={item.nodeLength} >{item.name}</td>
                                        </>
                                    }
                                    <td des="审批人员" className="px-5px py-2px" valign="top" rowSpan={node.renderNodeList.length + 1}>
                                        {
                                            (
                                                item.step_type != 8 && (tplData.StepInfo.step_type == 2 || (node.handle_id && node.handle_id == tplData.CurUserGUID) || (!node.handle_id && node.auditor_id && node.auditor_id == tplData.CurUserGUID) || item.step_define_id == tplData.StepInfo.step_define_id || !item.anonymous_approval || !item.anonymous_approval.Enable ||  item.anonymous_approval.Scopes.indexOf('"name"') == -1 || item.anonymous_approval.ExcludedActivityIds.indexOf(tplData.StepInfo.step_define_id) != -1)
                                            ) && <>
                                                    {
                                                        (
                                                            item.step_type == 1 || (item.step_type == 2 && node.node_status != 0)
                                                        )
                                                        ? <>{node.auditor_name}</>
                                                        : <>{node.handle_name}</>
                                                    }
                                                    {
                                                        (tplData.printSetting && tplData.printSetting.printApprovalOrg == 1 && node.station_name)
                                                        && <p des="审批组织">{node.station_name}</p>
                                                    }
                                                    {
                                                        (
                                                            node.handle_name 
                                                            && (
                                                                node.handle_mode == 6 
                                                                || node.handle_mode == 7 
                                                                || node.handle_mode == 8 
                                                                || (
                                                                    node.handle_name != node.auditor_name 
                                                                    && node.handle_mode == 0
                                                                )
                                                            )
                                                        ) 
                                                        && <>{node.handle_mode_text}</>
                                                    }
                                                </>
                                        }
                                    </td>
                                    <td des="审批意见" className="px-5px py-2px" valign="top">
                                        {
                                            (node.sign_img && item.step_type != 8)
                                            && <img src={node.sign_img} className="w-80px h-28px float-right ml-3" alt="签章" />
                                        }
                                        <div className="overflow-hidden text-justify whitespace-pre-wrap">
                                            {
                                                (
                                                    tplData.StepInfo.step_type == 2 
                                                    || (node.handle_id && node.handle_id == tplData.CurUserGUID) 
                                                    || item.step_define_id == tplData.StepInfo.step_define_id 
                                                    || !item.anonymous_approval 
                                                    || !item.anonymous_approval.Enable 
                                                    || item.anonymous_approval.Scopes.indexOf('"operate"') == -1 
                                                    || item.anonymous_approval.ExcludedActivityIds.indexOf(tplData.StepInfo.step_define_id) != -1
                                                )
                                                && <GetStepStatusText step={item} node={node} tplData={tplData}></GetStepStatusText>
                                            }
                                            {node.opinion}
                                            {
                                                node.agent
                                                && <span className="ml-5px">[{node.agent}]</span>
                                            }
                                        </div>
                                    </td>
                                    <td des="审批时间" className="px-5px py-2px" valign="top">{node.handle_on&&node.handle_on.replace(/:\d+$/ig,'')}</td>
                                </tr>
                                {
                                            (
                                                tplData.StepInfo.step_type == 2 || (node.handle_id && node.handle_id == tplData.CurUserGUID) || item.step_define_id == tplData.StepInfo.step_define_id || !item.anonymous_approval || !item.anonymous_approval.Enable ||  item.anonymous_approval.Scopes.indexOf('"operate"') == -1 || item.anonymous_approval.ExcludedActivityIds.indexOf(tplData.StepInfo.step_define_id) != -1
                                            ) && node.renderNodeList.map(function(obj, objIndex){
                                                return <tr key={objIndex}>
                                                    <td des="扩展审批意见" className="px-5px py-2px" valign="top">
                                                        { 
                                                            obj.node_type == 7
                                                            && <span>【{getApproveBtnName({approveType:"Consult", btnText:"协商", tplData: tplData})}】{obj.handle_name} {getApproveBtnName({approveType:"Consult", btnText:"协商", tplData: tplData})}给 {obj.consult_to_user}</span>
                                                        }
                                                        {
                                                            obj.node_type == 12
                                                            && <span>【{getApproveBtnName({approveType:"Assigned", btnText:"交办", tplData: tplData})}】{obj.handle_name} {getApproveBtnName({approveType:"Assigned", btnText:"交办", tplData: tplData})}给 {obj.assigned_to_user}</span>
                                                        }
                                                        
                                                        {
                                                            obj.node_type == 2 && obj.handle_name
                                                            && <span>【{getApproveBtnName({approveType:"ReplyConsult", btnText:"回复协商", tplData: tplData})}】{obj.handle_name} {getApproveBtnName({approveType:"ReplyConsult", btnText:"回复协商", tplData: tplData})}给 {obj.consult_replay_user}</span>
                                                        }
                                                        <div className="mt-10px text-justify whitespace-pre-wrap">
                                                            <span className="mx-5px">{obj.opinion}</span>
                                                            {
                                                                obj.agent
                                                                && <span>[{obj.agent}]</span>
                                                            }
                                                        </div>
                                                    </td>
                                                    <td className="px-5px py-2px" valign="top">{obj.handle_on && obj.handle_on.replace(/:\d+$/ig,'')}</td>
                                                </tr>
                                            })
                                        }
                            </React.Fragment>
                        })
                    })
                }
                </tbody>
            </table>
        </div>
    </div>;
}

//步骤数据清洗
function __getStepsDate({
    tplData
}){
    let returnSteps = [];//清洗后的数据
    if(tplData.ApproveSteps && tplData.ApproveSteps.length && tplData.show_audit_records == 1){
        var steps = [];
        var show_consult_records = tplData.hideInfo.show_consult_records;//
        var show_assigned_records = tplData.hideInfo.show_assigned_records;//
        tplData.ApproveSteps.forEach(function(step){
            if(step.step_type == 8){return};
            if(step.sub_process_instance && step.sub_process_instance.steps && step.sub_process_instance.steps.length){
                step.sub_process_instance.steps.forEach(function(s_step){
                    if(s_step.step_type !== 2){
                        //处理匿名
                        var anonymous_approval = s_step.anonymous_approval,
                            CurUserGUID = tplData.CurUserGUID,
                            parent_auditor_id = tplData.NodeInfo.parent_auditor_id;
                        if((s_step.nodes && s_step.step_define_id != (tplData.StepInfo && tplData.StepInfo.step_define_id) && anonymous_approval && anonymous_approval.Enable && JSON.parse(anonymous_approval.Scopes).length && anonymous_approval.ExcludedActivityIds.indexOf(tplData.StepInfo.step_define_id) == -1) && s_step.step_type != 2){
                            s_step.nodes.forEach(function(node){
                                if(node.handle_id == CurUserGUID || (!node.handle_id && node.auditor_id == CurUserGUID) || (parent_auditor_id && (parent_auditor_id == node.handle_id || (!node.handle_id && node.auditor_id == parent_auditor_id)))){
                                    s_step.CurUserIsPart = true;
                                }

                            });
                        }
                        s_step.is_sub_process = true;
                        steps.push(s_step);
                    }
                });
            }else{
                //处理匿名
                var anonymous_approval = step.anonymous_approval,
                    CurUserGUID = tplData.CurUserGUID,
                    parent_auditor_id = tplData.NodeInfo.parent_auditor_id;
                if((step.nodes && step.step_define_id != (tplData.StepInfo && tplData.StepInfo.step_define_id) && anonymous_approval && anonymous_approval.Enable && JSON.parse(anonymous_approval.Scopes).length && anonymous_approval.ExcludedActivityIds.indexOf(tplData.StepInfo.step_define_id) == -1) && step.step_type != 2){
                    step.nodes.forEach(function(node){
                        if(node.handle_id == CurUserGUID || (!node.handle_id && node.auditor_id == CurUserGUID) || (parent_auditor_id && (parent_auditor_id == node.handle_id || (!node.handle_id && node.auditor_id == parent_auditor_id)))){
                            step.CurUserIsPart = true;
                        }
                    });
                }
                steps.push(step);
            }
        });
        
        //格式化步骤路径
        /*
        step.step_type
        1 发起步骤
        4 普通步骤
        parallel 并行步骤
        5 子流程
        8 网关 | 分流 | 合流
        2 结束

        step.status
        0 未激活
        1 待办
        2 在办
        3 审批通过，已办结
        4 已交办
        -3 打回
        -2 作废
        -1 终止
        -10 关闭
        -4 步骤关闭
    */
        var data = steps.filter(function(item){
            var nodeLength = 0;
            //打印只展示已审或在审步骤且为非隐匿步骤
            if(
                [1, 2,3,0,-1,-2,-3].indexOf(item.status) != -1 && !(tplData.StepInfo.step_type != 2 
                && item.step_define_id != tplData.StepInfo.step_define_id 
                && item.anonymous_approval
                && item.anonymous_approval.Enable 
                && item.anonymous_approval.ExcludedActivityIds.indexOf(tplData.StepInfo.step_define_id) == -1
                && JSON.parse(item.anonymous_approval.Scopes).length == 6 && !item.CurUserIsPart)
            ){
                //只展示已审人员审批意见，包括表决自动作废
                var nodes = item.nodes.filter(function(node){
                    if([1,3,2,0,-1,-2,-3].indexOf(node.node_status) != -1 && (item.step_type != 8 || node.node_status == -2)){
                        nodeLength++;
                        var renderNodeList = node.extends_opinion.concat();
                        renderNodeList = renderNodeList.filter(function(n_node){
                            return n_node.handle_name;
                        });
                        if(show_consult_records && !show_assigned_records){
                            renderNodeList = renderNodeList.filter(function(n_node){
                                return n_node.node_type == 7 || n_node.node_type == 2;
                            });
                        }
                        if(!show_consult_records && show_assigned_records){
                            renderNodeList = renderNodeList.filter(function(n_node){
                                return n_node.node_type == 12;
                            });
                        }
                        if(!show_consult_records && !show_assigned_records){
                            renderNodeList = [];
                        }
                        
                        node.renderNodeList = renderNodeList;
                        if(node.renderNodeList && node.renderNodeList.length){
                            node.renderNodeList.forEach(function(obj){
                                if([7,12,2].indexOf(obj.node_type) != -1 && obj.handle_name){
                                    nodeLength++;
                                }
                            });
                        }
                        return true;
                    }
                });
                item.nodeLength = nodeLength;
                item.nodes = nodes;
                return true;
            }
        });
        //循环剔除已经隐藏的信息，不在模板里面隐藏，是因为序号的问题
        if(data.length >0){
            var ApproveSteps=[];
            for(var i=0;i<data.length;i++)
            {
                if(!(data[i].anonymous_approval.Scopes.indexOf('allstep') != -1  && data[i].step_define_id != tplData.StepInfo.step_define_id && data[i].anonymous_approval && data[i].anonymous_approval.Enable && data[i].anonymous_approval.ExcludedActivityIds.indexOf(tplData.StepInfo.step_define_id) == -1)) 
                {
                    ApproveSteps.push(data[i]);
                }
            }
            data = ApproveSteps;
        }
        returnSteps = data;
        // var approveOpinionHtml = template('approveOpinion_tpl',{data:data,tplData:tplData});
        // if(tplData.form.form_mode == $.formMode.custom){
        //     $('.print-form #approveStepsWrap').html(approveOpinionHtml);
        // } else {
        //     $('.form-runtime #approveStepsWrap').html(approveOpinionHtml);
        // }
    }
    return returnSteps;
}

//返回当前审批步骤审批状态
function GetStepStatusText({
    step,
    node,
    tplData
}){
    let returnText = "";
    if(step.step_type == 1){
        if (step.is_sub_process){
            if(node.expand_opinion){
                returnText = node.expand_opinion;
            }else{
                returnText = "同意";
            }
        }else{
            returnText = "发起";
        }
    }else if(step.step_type == 2 && node.node_status == 3){
        //<!--step_type == 2是结束节点 node_status == 3是已办-->
        returnText = "归档";
    }else if(step.step_type == 8){
        if(step.voted_status == 1){
            returnText = "表决同意";
        }else if(step.voted_status == 2){
            if(node.node_status == -2){
                returnText = getApproveBtnName({approveType:"Cancel", btnText:"作废", tplData: tplData});
            }else{
                returnText = "表决不同意";
            }
        }else{
            if(node.expand_opinion){
                returnText = node.expand_opinion;
            }else{
                returnText = "同意";
            }
        }
    }else if(node.node_status == 3 && !node.add_sign_users_text){
        if(node.voted_status == 1){
            returnText = "表决同意";
        }else if(node.voted_status == 2){
            returnText = "表决不同意";
        }else{
            if(node.expand_opinion){
                returnText = node.expand_opinion;
            }else{
                returnText ="同意"
            }
        }
    }else if(node.node_status == 3 && node.add_sign_users_text){
        returnText = getApproveBtnName({approveType:"AddSign", btnText:"加签", tplData: tplData});
    }else if(node.node_status == -3){
        returnText = getApproveBtnName({approveType:"RollBack", btnText:"驳回", tplData: tplData});
    }else if(node.node_status == -2){
        returnText = getApproveBtnName({approveType:"Cancel", btnText:"作废", tplData: tplData});
    }else if(node.node_status == -1){
        returnText = "终止";
    }
    if(returnText){
        return <>【{returnText}】</>;
    }else{
        return null;
    }
}